package com.yiren.dbaa.module.common.model;

import android.app.Activity;
import android.os.Build;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.yiren.dbaa.currency.api.CommonCallBack;
import com.yiren.dbaa.module.common.contract.PermissionContract;

import java.util.List;

/**
 * Created by WANGRONGXIANG
 * on 2022/6/28
 * Describe
 */
public class PermissionModel implements PermissionContract.Model {

    private Activity activity;

    public PermissionModel(Activity activity) {
        this.activity = activity;
    }

    @Override
    public void requestPermissions(String[] permissions, int versionCode, CommonCallBack callBack) {
        if (Build.VERSION.SDK_INT >= versionCode) {
            XXPermissions.with(activity)
                    .permission(permissions)
                    .request(new OnPermissionCallback() {
                        @Override
                        public void onGranted(List<String> permissions, boolean all) {
                            callBack.success("获取权限成功");
                        }
                        @Override
                        public void onDenied(List<String> permissions, boolean never) {
                            if (never) {
                                callBack.fail("被永久拒绝授权，请手动授予存储权限");
                                // 如果是被永久拒绝就跳转到应用权限系统设置页面
                                XXPermissions.startPermissionActivity(activity, permissions);
                            } else {
                                for (int i = 0; i < permissions.size(); i++) {
                                    if (Permission.MANAGE_EXTERNAL_STORAGE.equals(permissions.get(i))) {
                                        callBack.fail("获取权限失败");
                                        break;
                                    }
                                }
                            }
                        }
                    });
        } else {
            callBack.success("");
        }
    }

    @Override
    public boolean hasPermission(String[] permissions) {
        return XXPermissions.isGranted(activity, permissions);
    }
}
